<?php
namespace app\index\model;

use think\Db;
use think\Request;
use think\Config;
use think\Loader;
class Expense extends \think\Model
{

    /**
     *  写入消费记录
     *
     *      $expenseName:消费名称
     *      $expenseTypeName:表名
     *      $expenseTypeId:输入表的id
     *      $expenseOpenId:openId
     *      $expenseNote:消费备注
     *      $originalScore:账户余额
     *      $expenseCustomer:消费金额
     *      $balanceScore:消费后余额
     *      $expenseCustomer:查询一次消费的积分
     */
    public function setExpenseRecord($expenseName,$expenseTypeName,$expenseTypeId,$expenseOpenId,$expenseNote,$expenseCustomer){

        //获取消费前积分
        $originalScoreJson = $this -> getWxuserScore($expenseOpenId);
        $originalScoreArr = json_decode($originalScoreJson,true);
        $originalScore = $originalScoreArr['originalScore'];
        //计算消费后积分
        $balanceScore = intval($originalScore) - intval($expenseCustomer);

        //存储到个人账户
        $this -> setWxuserScore($expenseOpenId,$balanceScore);

        $insertExpenseData = array(
            'expense_name' => $expenseName,
            'type_name' => $expenseTypeName,
            'type_id' => $expenseTypeId,
            'openId' => $expenseOpenId,
            'note' => $expenseNote,
            'add_time' => time(),
            'original_score' => $originalScore,
            'consume_score' => $expenseCustomer,
            'balance_score' => $balanceScore
        );

        $expenseData = Db::name('expense_record') -> insert($insertExpenseData);
        if($expenseData){
            $ajax['status'] = 1;
            $ajax['msg'] = '成功消费一条记录';
            return json_encode($ajax);
        }else{
            $ajax['status'] = 0;
            $ajax['status'] = '消费失败';
            return json_encode($ajax);
        }
    }

    /*
     * 获取微信用户原积分情况
     */
    protected function getWxuserScore($openId){
        $userInfo = Db::name('wxuser') -> where('openId',$openId) -> field('score') -> find();

        $returnUserScore = array(
            'originalScore' => $userInfo['score']
        );
        return json_encode($returnUserScore);
    }

    /*
     * 设置微信用户积分余额
     */
    protected function setWxuserScore($openId,$score){
        $updateWxuser = array(
            'score' => $score
        );
        $resScore = Db::name('wxuser') -> where('openId',$openId) -> update($updateWxuser);
    }

}